package com.example.musicdemo.net

import com.example.musicdemo.util.ThreadUtil
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.*
import org.json.JSONObject
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

/**
 * des:发送网络请求类
 */
class NetManger private constructor() {
    private val client by lazy { OkHttpClient() }

    companion object {
        val manager by lazy { NetManger() }
    }

    fun <RESPONSE> sendRequest(req: MRequest<RESPONSE>) {
        val type = req.typeId
        val request = Request.Builder()
            .url(req.url)
            .get()
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                req.handler.onError(type, e.message.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                var result = response.body?.string()

                if (req.url.contains("/top/playlist?offset=")) {
                    val jsonObject = JSONObject(result)
                    result = jsonObject.getString("playlists")
                }

                if (req.url.contains("cloudsearch?keywords")) {
                    val jsonObject = JSONObject(result)
                    val jsonObject1 = jsonObject.getJSONObject("result")
                    result = jsonObject1.getString("songs")


                }
                val parseResult = req.parseResult(result)


                ThreadUtil.runOnMainThread {
                    req.handler.onSuccess(type, parseResult)
                }


            }

        })

    }




}